package daa.levelup.Library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;


public class DaoLibrary {

    public List<Book> getAllBooksFromDB()
    {
        List<Book> toReturn = new LinkedList<Book>();
        try
        {
            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            try
            {

                conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/myLibrary","root","root");
                ps = conn.prepareStatement("Select * from myLibrary.Books");
                rs = ps.executeQuery();
                Book book = null;
                while (rs.next())
                {
                    book = new Book(rs.getInt("id"), rs.getString("name"));
                    toReturn.add(book);
                }
            }
            finally
            {
                if (conn != null)
                {
                    conn.close();
                    conn = null;
                }
                if (ps != null)
                {
                    ps.close();
                    ps = null;
                }
                if (rs != null)
                {
                    rs.close();
                    rs = null;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return toReturn;
    }


    @SuppressWarnings("JpaQueryApiInspection")
    public boolean addBookToDB(Book book)
    {
        boolean f = false;
        try
        {
            Connection conn = null;
            PreparedStatement ps = null;
            try
            {
                conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/myLibrary","root","root");


                ps = conn.prepareStatement("Insert into  myLibrary.Books VALUES(?,?)");
                ps.setInt(1, book.getBookId());
                ps.setString(2, book.getBookName());


                int res = ps.executeUpdate();
                f = res > 0;
            }
            finally
            {
                if (conn != null)
                {
                    conn.close();
                    conn = null;
                }
                if (ps != null)
                {
                    ps.close();
                    ps = null;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return f;
    }

}

